package kr.couponplay.android.domain;

import java.util.HashMap;
import java.util.Map;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.Constants;
import kr.couponplay.android.support.cache.FileCache;
import kr.couponplay.android.support.cache.ImageLoader;
import android.content.Context;

public class BeanFactory {
	private static Map<Class<?>, Object> factory = new HashMap<Class<?>, Object>();
	
	public static <T> T getBean(Context applicationContext, Class<T> requiredType) {
		Object bean = factory.get(requiredType);
		if (bean == null) {
			try {
				bean = requiredType.newInstance();
				if (bean instanceof AppContextAware) {
					((AppContextAware) bean).setApplicationContext(applicationContext);
				}
				if (bean instanceof FileCacheAware) {
					((FileCacheAware) bean).setFileCache(new FileCache(AppContext.getFileCacheRootPath(applicationContext) + Constants.DATA_CACHE_DEAL_PATH));
				}
				if (bean instanceof ImageLoader) {
					((ImageLoader) bean).initialze(AppContext.getFileCacheRootPath(applicationContext) + Constants.IMAGE_CACHE_DEAL_PATH);
				}
			} catch (Exception e) {
				new IllegalArgumentException(e);
			}
			factory.put(requiredType, bean);
		}
		return requiredType.cast(bean);
	}
}
